package com.yihaodian.server.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.servlet.Context.SContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yihaodian.api.common.Configs;
import com.yihaodian.api.search.SearchException;
import com.yihaodian.common.util.NetUtil;
import com.yihaodian.server.SearchServiceExporter;

/**
 * Spring -> Guice (NodeBootstrap)
 * 
 */
public class BootstrapContextListener extends ContextLoaderListener {
	private static final Logger logger = Logger
			.getLogger(BootstrapContextListener.class);

	@Override
	public void contextInitialized(ServletContextEvent event) {
		logger.info("BootstrapListener.init()");

		String location = System.getProperty(Configs.cluster_config_key);
		if (location == null) {
			logger.info("set " + Configs.cluster_config_key + " --> "
					+ Configs.cluster_config_default);
			System.setProperty(Configs.cluster_config_key,
					Configs.cluster_config_default);
		}
		logger.info(Configs.cluster_config_key + " = "
				+ Configs.cluster_config_default);
			
		

		super.contextInitialized(event);

		String host = null;
		int port = -1;

		ServletContext context = event.getServletContext();

		// jetty env
		if (context instanceof SContext) {
			SContext scontext = (SContext) context;
			ContextHandler handler = scontext.getContextHandler();
			port = handler.getServer().getConnectors()[0].getPort();
			host = handler.getServer().getConnectors()[0].getHost();
		} else {
			String sPort = Configs.get(Configs.node_port_key);
			if (sPort == null)
				throw new SearchException("can not get node port");
			port = Integer.parseInt(sPort);
		}
		if (host == null)
			host = NetUtil.localAddress();

		ApplicationContext appContext = WebApplicationContextUtils
				.getWebApplicationContext(context);
		SearchServiceExporter exporter = (SearchServiceExporter) appContext
				.getBean("searchService");

		exporter.startup(port);
		logger.info("start node in web " + host + " " + port);
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		super.contextDestroyed(event);
	}

}
